package cc.liyinghao.controller;

import cc.liyinghao.param.UserLoginParam;
import cc.liyinghao.param.UserRegisterParam;
import cc.liyinghao.param.ValidationPhoneNumberParam;
import cc.liyinghao.common.pojo.SysUser;
import cc.liyinghao.security.util.SecurityUtil;
import cc.liyinghao.service.UserService;
import cc.liyinghao.common.api.Result;
import cc.liyinghao.response.LoginSuccessfulVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


/**
 * 用户管理
 */
@RestController
@Slf4j
@RequestMapping("/user")
@RequiredArgsConstructor
@Api(tags = "用户路由")
public class UserController {

    final private UserService userService;

    @GetMapping("/hello")
    @ApiOperation(value = "服务器测试")
    public String test() {
        System.out.println(SecurityUtil.getCurrentUsername());
        System.out.println(SecurityUtil.getCurrentUserId());
        return "ok";
    }

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public Result<String> register(@Validated @RequestBody UserRegisterParam userRegisterParam) {
        SysUser user = userService.register(userRegisterParam);
        if (user == null) {
            return Result.error("注册失败,用户名或手机号已存在");
        }
        return Result.success("注册成功");
    }

    @ApiOperation(value = "手机号验证，发送验证码")
    @PostMapping("/validation_phone_number")
    public Result<String> validationPhoneNumber(@Validated @RequestBody ValidationPhoneNumberParam validationPhoneNumberParam) {
        userService.getValidationPhoneNumberCode(validationPhoneNumberParam.getPhoneNumber());
        return Result.success("验证码发送成功");
    }

    @ApiOperation(value = "用户切换头像")
    @PostMapping("/change_avatar")
    public Result<String> changeAvatar(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        //1.校验是否为空
        if (multipartFile.isEmpty()) {
            return Result.error("图片上传失败");
        }
        String newURL = userService.updateAvatar(multipartFile, SecurityUtil.getCurrentUserId());
        return Result.success(newURL);
    }

    @ApiOperation(value = "登录") //返回token与用户基本信息
    @PostMapping("/login")
    public Result<LoginSuccessfulVo> login(@Validated @RequestBody UserLoginParam userLoginParam) {
        LoginSuccessfulVo loginSuccessfulVo = userService.login(userLoginParam.getUsername(), userLoginParam.getPassword());
        if (loginSuccessfulVo == null) {
            return Result.error("用户名或密码错误");
        }
        return Result.success(loginSuccessfulVo);
    }
}